package com.atguigu.springboot.controller;

import com.atguigu.springboot.dao.DepartmentDao;
import com.atguigu.springboot.dao.EmployeeDao;
import com.atguigu.springboot.entities.Department;
import com.atguigu.springboot.entities.Employee;
import com.atguigu.springboot.mapper.DepartmentMapper;
import com.atguigu.springboot.mapper.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.List;
import java.util.Map;

@Controller
public class EmployeeController {
	@Autowired
	EmployeeDao employeeDao;
	@Autowired
	DepartmentDao departmentDao;
	@Autowired
	JdbcTemplate jdbcTemplate;
	@Autowired
	EmployeeMapper employeeMapper;
	@Autowired
	DepartmentMapper departmentMapper;
	
	//查询所有员工
	@GetMapping("/emps")
	public String emps(Model model){
		Collection<Employee> all = employeeDao.getAll();
		model.addAttribute("emps",all);
		return "emp/list";
	}
	
	//去添加员工页面
	@GetMapping("/emp")
	public String toAddPage(Model model){
		Collection<Department> departments = departmentDao.getDepartments();
		model.addAttribute("depts",departments);
		return "emp/add";
	}
	
	//添加员工
	@PostMapping("/emp")
	public String addEmp(Employee employee){
		employeeDao.save(employee);
		return "redirect:/emps";
	}
	
	//去编辑页面
	@GetMapping("/emp/{id}")
	public String toEditPage(@PathVariable("id") Integer id, Model model){
		Employee employee = employeeDao.get(id);
		model.addAttribute("emp",employee);
		
		Collection<Department> departments = departmentDao.getDepartments();
		model.addAttribute("depts",departments);
		return "emp/add";
	}
	
	//修改员工
	@PutMapping("/emp")
	public String updateEmp(Employee employee){
		employeeDao.save(employee);
		return "redirect:/emps";
	}
	
	//删除员工
	@DeleteMapping("/emp/{id}")
	public String deleteEmp(@PathVariable("id") Integer id){
		employeeDao.delete(id);
		return "redirect:/emps";
	}
	
	//数据库测试
	@ResponseBody
	@RequestMapping("/department")
	public List<Map<String, Object>> searchDepartment(){
		List<Map<String, Object>> maps = jdbcTemplate.queryForList("select * from department");
		return maps;
	}
	
	//mybatis配置文件版测试
	@ResponseBody
	@RequestMapping("/employee")
	public List<Employee> getEmpAll(){
		return employeeMapper.getEmpList();
	}
	
	@ResponseBody
	@RequestMapping("/deptall")
	public List<Department> getDeptAll(){
		return departmentMapper.getDeptById();
	}
	
}
